import java.util.Timer;
import java.util.concurrent.PriorityBlockingQueue;

//这里继承Comparable是为解决“忙等”问题
class MyTask1 implements Comparable<MyTask1>{
    //创建一个任务
    private Runnable runnable;
    //规定一个时间
    private long time;

    public MyTask1 (Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run(){
        runnable.run();
    }
    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTask1 o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer1{
    private PriorityBlockingQueue<MyTask1> queue = new PriorityBlockingQueue<>();

    public void scheduler(Runnable runnable, long time){
        MyTask1 task1 = new MyTask1(runnable,time);
        queue.put(task1);
        //每次任务执行之后，都唤醒一下扫描线程
        synchronized (this){
            this.notify();
        }
    }
    //实现一个构造方法
    public MyTimer1(){
        //创建一个线程
        Thread thread = new Thread(() ->{
           while(true){
               try {
                   //取出队首元素
                   MyTask1 task1 = queue.take();
                   //获取当前的时间
                   long curTimer = System.currentTimeMillis();
                   //当前时间与约定时间进行比较，如果
                   if(curTimer < task1.getTime()){
                       queue.put(task1);
                       //进行一个等待时间
                       synchronized (this){
                           this.wait(task1.getTime() - curTimer);
                       }
                   }else{
                       //时间到了，进行执行任务
                       task1.run();
                   }
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        thread.start();
    }
}
public class Test3 {
    public static void main(String[] args) {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
            }
        },300);
        System.out.println("main");
    }
}
